
//
//  HJOAuthViewController.m
//  12期传智微博HJ
//
//  Created by mac on 15-2-3.
//  Copyright (c) 2015年 jun. All rights reserved.
//

#import "HJOAuthViewController.h"
#import "HJNewfeatureViewController.h"
#import "HJWelcomViewController.h"


#define HJAuthorizeUrl @"https://api.weibo.com/oauth2/authorize"
#define HJclientId @"905280735"
#define HJClientSecret @"9b2b483ba83d7e35fa165c6552657add"
#define HJRedirectUri  @"http://ios.itcast.cn"

#define HJAccessTokenUrl @"https://api.weibo.com/oauth2/access_token"


@interface HJOAuthViewController ()<UIWebViewDelegate>

@end

@implementation HJOAuthViewController

- (void)loadView
{
    self.view = [[UIWebView alloc]init];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化导航条
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    //加载登录界面
    [self loadOAuthPage];
    
}
- (void)loadOAuthPage
{
    //拼接请求路径
    NSString *urlString = [NSString stringWithFormat:@"%@?client_id=%@&redirect_uri=%@",HJAuthorizeUrl,HJclientId,HJRedirectUri];
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //加载网页
    UIWebView *webView = (UIWebView *)self.view;
    
    webView.delegate = self;
    [webView loadRequest:request];
}
#pragma mark - UIWebViewDelegate
// 只要webview发送请求就会调用
// request,webview即将要请求的地址
// 返回YES代表允许继续加载, 返回NO代表不允许加载
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    //判断即将要请求的url是否包含code=,如果包含证明拿到了授权
    NSString *urlstring = request.URL.absoluteString;
    NSRange range = [urlstring rangeOfString:@"code="];
    if (range.location != NSNotFound) {
        //截取获取到的requesttoken 换取accesstoken
        NSUInteger startIndex = range.location + range.length;
        NSString *code = [urlstring substringFromIndex:startIndex];
        [self accessTokenWithCode:code];
        return NO;
        
    }
    return YES;
}
/**
 *  根据已经授权的RequestToken 换取AccessToken
 
 */
- (void)accessTokenWithCode:(NSString *)code
{
    //封装请求菜蔬
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"client_id"]  = HJclientId;
    parameters[@"client_secret"]  = HJClientSecret;
    parameters[@"grant_type"]  = @"authorization_code";
    parameters[@"code"]  = code;
    parameters[@"redirect_uri"]  = HJRedirectUri;
    //创建网络管理请求对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //支持text/plain
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    //利用管理对象发送请求
    [manager POST:HJAccessTokenUrl parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSLog(@"换取accrsstoken成功");
        //将服务器返回的字典转成模型
        HJAccount *account = [HJAccount objectWithKeyValues:responseObject];
        //将模型存到沙盒中
        [account save];
        //判断显示新特性还是欢迎画面
        [[UIApplication sharedApplication].keyWindow chooseRootViewController];
        [SVProgressHUD dismiss];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"换取失败===%@",error);
        
            }];
    
    
    }
//开始加载网页时调用
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [SVProgressHUD showWithStatus:@"俊哥正在帮你加载...."];
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [SVProgressHUD dismiss];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [SVProgressHUD dismiss];
}
- (void)close
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
